package com.kmproject.haifu.mvp.presenter;

import android.app.Activity;
import android.app.Application;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.widget.CustomPopupWindow;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.RxUtils;
import com.kmproject.haifu.mvp.contract.MemberUpdatelevelPaymentContract;
import com.kmproject.haifu.mvp.model.api.Api;
import com.kmproject.haifu.mvp.model.entity.ResultBean;
import com.kmproject.haifu.mvp.model.entity.beans.ExchangeRateBean;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.beans.MemberCenterUserInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.MemberFeatureBean;
import com.kmproject.haifu.mvp.model.entity.beans.MemberPayResultBean;
import com.kmproject.haifu.mvp.ui.adapter.MemberCenterPayWayAdapter;
import com.xgr.easypay.EasyPay;
import com.xgr.easypay.alipay.AliPay;
import com.xgr.easypay.alipay.AlipayInfoImpli;
import com.xgr.easypay.callback.IPayCallback;
import com.xgr.easypay.wxpay.WXPay;
import com.xgr.easypay.wxpay.WXPayInfoImpli;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

//import com.xgr.easypay.EasyPay;
//import com.xgr.easypay.alipay.AliPay;
//import com.xgr.easypay.alipay.AlipayInfoImpli;
//import com.xgr.easypay.callback.IPayCallback;
//import com.xgr.easypay.wxpay.WXPay;
//import com.xgr.easypay.wxpay.WXPayInfoImpli;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/20/2019 13:40
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@FragmentScope
public class MemberUpdatelevelPaymentPresenter extends BasePresenter<MemberUpdatelevelPaymentContract.Model, MemberUpdatelevelPaymentContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    int selectPayWayInde;
    CustomPopupWindow customPopupWindow;//支付

    @Inject
    public MemberUpdatelevelPaymentPresenter(MemberUpdatelevelPaymentContract.Model model, MemberUpdatelevelPaymentContract.View rootView) {
        super(model, rootView);
    }

    /**
     * 支付宝支付
     *
     * @param activity
     * @param datas
     */
    public void payForAli(Activity activity, String datas) {
        //实例化支付宝支付策略
        AliPay aliPay = new AliPay();
        //构造支付宝订单实体。一般都是由服务端直接返回。
        AlipayInfoImpli alipayInfoImpli = new AlipayInfoImpli();
        alipayInfoImpli.setOrderInfo(datas);
        //策略场景类调起支付方法开始支付，以及接收回调。
        EasyPay.pay(aliPay, activity, alipayInfoImpli, new IPayCallback() {
            @Override
            public void success() {
                mRootView.memberPaySuccess(null);
                mRootView.showMessage("支付成功");
                customPopupWindow.dismiss();
            }

            @Override
            public void failed() {
                mRootView.showMessage("支付失败");
            }

            @Override
            public void cancel() {
                mRootView.showMessage("支付取消");
            }
        });
    }

    /**
     * 微信支付
     *
     * @param activity
     * @param memberPayResultBean
     */
    public void payForWX(Activity activity, MemberPayResultBean memberPayResultBean) {
//        PayReq request = new PayReq();
//        request.appId = memberPayResultBean.getAppid();
//        request.partnerId = memberPayResultBean.getPartnerid();
//        request.prepayId = memberPayResultBean.getPrepayid();
//        request.packageValue = memberPayResultBean.getPackageX();
//        request.nonceStr = memberPayResultBean.getNoncestr();
//        request.timeStamp = memberPayResultBean.getTimestamp();
//        request.sign = memberPayResultBean.getSign();
//        WxApiUtils.getWxApi(mAppManager.getCurrentActivity()).sendReq(request);


        //实例化微信支付策略
//        String wxAppId = "";
        WXPay wxPay = WXPay.getInstance(activity, memberPayResultBean.getAppid());
        //构造微信订单实体。一般都是由服务端直接返回。
        WXPayInfoImpli wxPayInfoImpli = new WXPayInfoImpli();
        wxPayInfoImpli.setTimestamp(memberPayResultBean.getTimestamp());
        wxPayInfoImpli.setSign(memberPayResultBean.getSign());
        wxPayInfoImpli.setPrepayId(memberPayResultBean.getPrepayid());
        wxPayInfoImpli.setPartnerid(memberPayResultBean.getPartnerid());
        wxPayInfoImpli.setAppid(memberPayResultBean.getAppid());
        wxPayInfoImpli.setNonceStr(memberPayResultBean.getNoncestr());
        wxPayInfoImpli.setPackageValue(memberPayResultBean.getPackageX());
        //策略场景类调起支付方法开始支付，以及接收回调。
        EasyPay.pay(wxPay, activity, wxPayInfoImpli, new IPayCallback() {
            @Override
            public void success() {
                mRootView.memberPaySuccess(null);
                mRootView.showMessage("支付成功");
                customPopupWindow.dismiss();
            }

            @Override
            public void failed() {
                mRootView.showMessage("支付失败");
            }

            @Override
            public void cancel() {
                mRootView.showMessage("支付取消");
            }
        });
    }

    /**
     * 微信支付成功
     */
    public void wxPaySuccess() {
        mRootView.memberPaySuccess(null);
        customPopupWindow.dismiss();
    }

    /**
     * 获取字典表支付方式
     */
    public void dictList(List<HousePayWayBean> mhousePayWayBeans) {
        if (mhousePayWayBeans != null && !mhousePayWayBeans.isEmpty()) {
            mRootView.dictListSuccess(mhousePayWayBeans);
            return;
        }
        mModel.dictList(Api.PAY_METHOD, "").compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<HousePayWayBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<HousePayWayBean>> listResultBean) {
                        if (AppUtil.isSuccess(listResultBean)) {
                            mRootView.dictListSuccess(listResultBean.getData());
                        } else {
                            mRootView.showMessage(listResultBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 获取汇率的id
     *
     * @param memberFeatureBeans
     * @return
     */
    public String getConfigureId(List<MemberFeatureBean> memberFeatureBeans) {
        if (memberFeatureBeans == null || memberFeatureBeans.isEmpty()) {
            return "";
        }
        for (MemberFeatureBean memberFeatureBean : memberFeatureBeans) {
            if (memberFeatureBean.getValues() != null && !memberFeatureBean.getValues().isEmpty()) {

                for (MemberFeatureBean.FeatureValue featureValue : memberFeatureBean.getValues()) {
                    if ("exchangeRate".equals(featureValue.getFunctionCode())) {
                        return featureValue.getConfigureId();
                    }
                }
            }
        }
        return "";
    }

    /**
     * 获取实时汇率
     *
     * @param configureId   特权里面的汇率id
     * @param upgradeRuleId 规则id
     */
    public void getExchangeRate(String configureId, String upgradeRuleId) {
        mModel.getExchangeRate(configureId, upgradeRuleId).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<ExchangeRateBean>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<ExchangeRateBean> exchangeRateBeanResultBean) {
                        if (AppUtil.isSuccess(exchangeRateBeanResultBean)) {
                            mRootView.getExchangeRateSuccess(configureId, exchangeRateBeanResultBean.getData());
                        } else {
                            mRootView.showMessage(exchangeRateBeanResultBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 支付宝支付
     *
     * @param activity
     * @param maps
     * @param housePayWayBean
     */
    public void memberpayForAli(Activity activity, Map<String, Object> maps, HousePayWayBean housePayWayBean) {
        mModel.memberPayForAli(maps).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<String>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<String> stringResultBean) {
                        if (AppUtil.isSuccess(stringResultBean)) {
                            payForAli(activity, stringResultBean.getData());
                        } else {
                            mRootView.showMessage(stringResultBean.getMessage());
                        }


                    }
                });
    }

    /**
     * 微信支付
     *
     * @param maps
     */
    public void memberPay(Activity activity, Map<String, Object> maps, HousePayWayBean housePayWayBean) {
        mModel.memberPay(maps).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<MemberPayResultBean>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<MemberPayResultBean> memberPayResultBeanResultBean) {
                        if (AppUtil.isSuccess(memberPayResultBeanResultBean)) {
                            if (!AppUtil.isWxAppInstalledAndSupported(activity)) {
                                mRootView.showMessage("使用微信支付，请选安装微信应用");
                                return;
                            }
                            //微信
                            payForWX(activity, memberPayResultBeanResultBean.getData());
                        } else {

                            mRootView.showMessage(memberPayResultBeanResultBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 支付弹框
     */
    public void payPopuWindow(String configureId, Activity activity, View mParentView, List<HousePayWayBean> housePayWayBeans, ExchangeRateBean exchangeRateBean, MemberCenterUserInfoBean.MemberLevelBean memberLevelBean, MemberCenterUserInfoBean.MemberLevelBean dqhydj
            , MemberCenterUserInfoBean memberCenterUserInfoBean) {
        if (exchangeRateBean == null || housePayWayBeans == null) {
            return;
        }

        selectPayWayInde = -1;
        customPopupWindow = new CustomPopupWindow.Builder().parentView(mParentView).contentView(CustomPopupWindow.inflateView(activity, R.layout.popuwindow_pay)).backgroundDrawable(activity.getResources().getDrawable(R.drawable.button_white_bg))
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isWrap(true).isHaveBackGround(true).isShowBottom(true).build();
        View view1 = customPopupWindow.getContentView();

        LinearLayout popuwindowPayClose = (LinearLayout) view1.findViewById(R.id.popuwindow_pay_close);
        TextView popuwindowPayJrhl = (TextView) view1.findViewById(R.id.popuwindow_pay_jrhl);
        TextView popuwindowPayDqhlyh = (TextView) view1.findViewById(R.id.popuwindow_pay_dqhlyh);
        TextView popuwindowPayDqhl = (TextView) view1.findViewById(R.id.popuwindow_pay_dqhl);
        TextView popuwindow_pay_money = (TextView) view1.findViewById(R.id.popuwindow_pay_money);
        popuwindowPayJrhl.setText("1:" + exchangeRateBean.getCnyExchangeRate());
        if (exchangeRateBean.getRebate() != null && !TextUtils.isEmpty(exchangeRateBean.getRebate()) && Double.parseDouble(exchangeRateBean.getRebate()) > 0 && Double.parseDouble(exchangeRateBean.getRebate()) < 10) {
            popuwindowPayDqhlyh.setText("当前汇率(已优惠" + exchangeRateBean.getRebate() + "折)");
        } else {
            //没有优惠
            popuwindowPayDqhlyh.setVisibility(View.GONE);
            popuwindowPayDqhl.setVisibility(View.GONE);
        }

        popuwindowPayDqhl.setText("1:" + exchangeRateBean.getCnyDiscountExchangeRate());
        popuwindow_pay_money.setText("￥ " + AppUtil.getShowMenoy(exchangeRateBean.getDiscountAmount()));
        RecyclerView popuwindow_pay_RecyclerView = (RecyclerView) view1.findViewById(R.id.popuwindow_pay_RecyclerView);
        popuwindow_pay_RecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        MemberCenterPayWayAdapter memberCenterPayWayAdapter = new MemberCenterPayWayAdapter(housePayWayBeans, new MemberCenterPayWayAdapter.ItemClickBack() {
            @Override
            public void callBack(int selectIndex) {
                selectPayWayInde = selectIndex;
            }
        });
        popuwindow_pay_RecyclerView.setAdapter(memberCenterPayWayAdapter);

        TextView popuwindowPaySure = (TextView) view1.findViewById(R.id.popuwindow_pay_sure);
        popuwindowPaySure.setText("确认支付 ￥ " + exchangeRateBean.getDiscountAmount());
        popuwindowPaySure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectPayWayInde < 0) {
                    mRootView.showMessage("请选择支付方式");
                    return;
                }
//                alipay
                Map<String, Object> maps = new HashMap<>();
                maps.put("upgradeRuleId", memberLevelBean.getMemberUpgradeRuleId());
                maps.put("payWay", memberCenterPayWayAdapter.getData().get(selectPayWayInde).getCategory());
                maps.put("tradeType", "APP");
                maps.put("memberLevelId", memberLevelBean.getMemberLevelId());
                maps.put("configureId", configureId);
                maps.put("description", "Android移动端 购买" + dqhydj.getLevelName() + "的" + memberLevelBean.getRuleName() + "套餐");

                if ("alipay".equals(memberCenterPayWayAdapter.getData().get(selectPayWayInde).getCategory())) {
                    memberpayForAli(activity, maps, memberCenterPayWayAdapter.getData().get(selectPayWayInde));
                } else {
                    memberPay(activity, maps, memberCenterPayWayAdapter.getData().get(selectPayWayInde));
                }

            }
        });

        popuwindowPayClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customPopupWindow.dismiss();
            }
        });
        customPopupWindow.show();
    }

    /**
     * 获取当前会员的自己的等级的特权
     *
     * @param memberLevelId
     */
    public void getMemberFunctionConfigureForNow(String memberLevelId) {

        mModel.getMemberFunctionConfigure(memberLevelId).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<MemberFeatureBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<MemberFeatureBean>> listResultBean) {
                        if (AppUtil.isSuccess(listResultBean)) {
                            mRootView.getMemberFunctionConfigureSuccessForNow(listResultBean.getData());
                        } else {
                            mRootView.showMessage(listResultBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 获取会员特权信息，根据特权id
     *
     * @param memberLevelId
     */
    public void getMemberFunctionConfigure(String memberLevelId, List<MemberFeatureBean> memberFeatureBeans) {
        if (memberFeatureBeans != null && !memberFeatureBeans.isEmpty()) {
            mRootView.getMemberFunctionConfigureSuccess(memberFeatureBeans);
            return;
        }
        mModel.getMemberFunctionConfigure(memberLevelId).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<MemberFeatureBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<MemberFeatureBean>> listResultBean) {
                        if (AppUtil.isSuccess(listResultBean)) {
                            mRootView.getMemberFunctionConfigureSuccess(listResultBean.getData());
                        } else {
                            mRootView.showMessage(listResultBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 获取升级规则
     *
     * @param memberLevelId
     * @param isAutoRenew
     */
    public void getMemberUpgradeRuleList(String memberLevelId, String isAutoRenew, List<MemberCenterUserInfoBean.MemberLevelBean> memberLevelBeans) {
        if (memberLevelBeans != null && !memberLevelBeans.isEmpty()) {
            mRootView.getMemberUpgradeRuleListSuccess(memberLevelBeans);
            return;
        }
        mModel.getMemberUpgradeRuleList(memberLevelId, isAutoRenew).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<MemberCenterUserInfoBean.MemberLevelBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<MemberCenterUserInfoBean.MemberLevelBean>> listResultBean) {
                        if (AppUtil.isSuccess(listResultBean)) {

                            mRootView.getMemberUpgradeRuleListSuccess(listResultBean.getData());
                            return;
                        }
                        mRootView.showMessage(listResultBean.getMessage());
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }
}
